from os.path import isfile
import numpy as np


class Micaps():
    def __init__(self, hsize=22):
        # self.fname = fname
        self.heads = []
        self.hsize = hsize

    def read(self, fname):
        # check file exist
        # fname = self.fname
        if not isfile(fname):
            return None

        # read contents
        encodings = ['utf-8', 'GBK']
        for encoding in encodings:
            txt = None
            try:
                with open(fname, 'r', encoding=encoding) as f:
                    txt = f.read().replace('\n', ' ').split()
                    f.close()
                    break
            except Exception:
                pass
        if txt is None:
            print("Micaps 4 file error: " + fname)
            return None

        # extract data
        self.heads = txt[:22]
        nlon = int(txt[15])
        nlat = int(txt[16])
        if nlon != 187 or nlat != 224:
            return None
        data = (np.array(txt[22:])).astype(np.float32)
        data.shape = [nlat, nlon]

        return data

    def write(self, fname, data, head1=None):
        encoding = 'GBK'
        h = self.heads
        heads = []
        heads.append(str.format(str('%s ' * 3) + '\n') % (h[0], h[1], h[2]))
        heads.append(str.format(str('%s ' * 6) + '\n') % (h[3], h[4], h[5], h[6], h[7], h[8]))
        heads.append(str.format(str('%s ' * 8) + '\n') % (h[9], h[10], h[11], h[12], h[13], h[14], h[15], h[16]))
        heads.append(str.format(str('%s ' * 5) + '\n') % (h[17], h[18], h[19], h[20], h[21]))
        if head1 is not None:
            heads[1] = head1

        # try:
        with open(fname, 'w', encoding=encoding) as f:
            f.writelines(heads)
            h = data.shape[0]
            for i in range(h):
                # line = [str(round(x,2))+' ' for x in data[i]]
                line = ['%.2f ' % x for x in data[i]]
                line1 = ''.join(line) + '\n'
                f.write(line1)
            f.close()

        return True
